/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxControlToolkit;

namespace NS_Controls
{
	/// <summary>
	/// Summary description for TextBoxField
	/// </summary>
	public class TextBoxField : BoundField
	{
		public TextBoxField()
		{
		}

		protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
		{
			Control child = null;
			Control control2 = null;
	 		if ((((rowState & DataControlRowState.Edit) != DataControlRowState.Normal) && !this.ReadOnly) || (((rowState & DataControlRowState.Insert) != DataControlRowState.Normal) && !this.ReadOnly))
			{
				TextBox box = new TextBox();
				box.ID = "txt_" + this.DataField;
				box.ToolTip = this.HeaderText;
				child = box;
				if ((this.DataField.Length != 0) && ((rowState & DataControlRowState.Edit) != DataControlRowState.Normal))
				{
					control2 = box;
				}
			}
			else if (this.DataField.Length != 0)
			{
				control2 = cell;
			}
			if (child != null)
			{
				cell.Controls.Add(child);
				if (this.DataFormatString == "{0:yyyy-MM-dd}" || this.DataFormatString == "{0:yyyy-MM-dd HH:mm:ss}")
				{
					((TextBox)child).Attributes.Add("onfocus", "ShowPopupCalendar(this);");
					((TextBox)child).Attributes.Add("onblur", "HidePopupCalendar();");
					((TextBox)child).Attributes.Add("format", this.DataFormatString.Substring(3, this.DataFormatString.Length - 4));
				}
			}
			if ((control2 != null) && base.Visible)
			{
				control2.DataBinding += new EventHandler(this.OnDataBindField);
			}
		}

		protected override void OnDataBindField(object sender, EventArgs e)
		{
			int nColumns = 0;
			if (sender is TextBox)
				nColumns = ((TextBox)sender).Columns;

			base.OnDataBindField(sender, e);

			if (sender is TextBox)
				if (((TextBox)sender).Columns == 5 && ((TextBox)sender).Columns != nColumns)	// For primitive data types OnDataBindField sets Columns == 5
					((TextBox)sender).Columns = nColumns;										// Reset Columns to previous value
		}
	}
}
